package controllers;

import java.util.ArrayList;
import java.util.List;

import models.Book;
import models.Cartoon;

import org.apache.commons.lang.StringUtils;

import play.Logger;
import play.cache.Cache;
import play.data.validation.Error;
import play.data.validation.Valid;
import play.data.validation.Validation;
import play.mvc.Controller;
import utils.Constants;

public class Author extends Controller {

	protected static final String FROM_ADDING_FORM = "addingauthor";
	
    public static void index() {
        render();
    }
    
    public static void displayList(final Long authorId) {
    	displayList(authorId, false);
    }
    
    public static void displayList(final Long authorId, final boolean isCartoonist) {
    	
    	models.Author author = models.Author.findById(authorId);
    	List<Book> bookList;
    	List<Cartoon> cartoonList;
    	if (isCartoonist) {
    		bookList = new ArrayList<Book>();
        	cartoonList = Cartoon.find("byCartoonist", author).fetch();
    	} else {
    		bookList = Book.find("byAuthor", author).fetch();
        	cartoonList = Cartoon.find("byWriter", author).fetch();
    	} 

    	render(author, isCartoonist, bookList, cartoonList);
    }

    
    public static void addForm(final String from) {
    	
    	Cache.set(Security.getSessionId() + Constants.FROM_KEY_CALL_ADDAUTHOR, from, "30mn");
    	
    	render();
    }
    
    /**
     * Add the author.
     * @throws Throwable 
     */
    public static void add(@Valid final models.Author author) throws Throwable {
    	
    	String from = (String) Cache.get(Security.getSessionId() + Constants.FROM_KEY_CALL_ADDAUTHOR);
    	if (Validation.hasErrors()) {
    		internalPerformError();
    		addForm(from);
    	} 
    	
    	// create author
    	author.create();
    	
    	if (StringUtils.isNotEmpty(from)) {
    		if (BookMngt.FROM_ADDING_FORM.equals(from)) {
    			String from2 = (String) Cache.get(Security.getSessionId() + Constants.FROM_KEY_CALL_ADDBOOK);
    			BookMngt.addForm(from2);
    			//TODO garder dans le cache ou en session les trucs saisis avant dans la fiche
    		} else if (CartoonMngt.FROM_ADDING_FORM.equals(from)) {
    			String from2 = (String) Cache.get(Security.getSessionId() + Constants.FROM_KEY_CALL_ADDCARTOON);
    			CartoonMngt.addForm(from2);
    			//TODO garder dans le cache ou en session les trucs saisis avant dans la fiche
    		} else {
    			error("Je sais pas où est : " + from);
    		}
    	} else {
    		error("Je ne sais pas d'où je viens");
    	}
    }
    
    
    private static void internalPerformError() {
    	
		if (Logger.isDebugEnabled()) {
			Logger.debug("Erreur trouvée dans création author");
			for (Error err : Validation.errors()) {
				Logger.debug(err.message() + " --> pour le champ " + err.getKey());
			}
		}
		
		params.flash(); // add http parameters to the flash scope
		validation.keep(); // keep the errors for the next request
    
    }
    
}
